package org.folio.rest.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import io.vertx.core.AsyncResult;
import io.vertx.core.Context;
import io.vertx.core.Handler;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import org.folio.rest.impl.other.PartyUtil;
import org.folio.rest.jaxrs.model.PartyLogCollection;
import org.folio.rest.jaxrs.model.PartyLogGroup;
import org.folio.rest.jaxrs.resource.PartyLog;
import org.folio.rest.persist.PgUtil;
import org.folio.rest.persist.cql.CQLWrapper;
import org.folio.rest.tools.utils.ValidationHelper;

import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static io.vertx.core.Future.succeededFuture;

/**
 * @author lee
 * @Classname PartyLog
 * @Description TODO
 * @Date 2020/6/18 16:40
 * @Created by lee
 */
public class PartyLogImpl implements PartyLog {
    private final Logger logger = LoggerFactory.getLogger("modparty");
    
    private static final String NOTIFY_TABLE = "party_log";


    @Override
    public void postPartyLog(String lang, org.folio.rest.jaxrs.model.PartyLog entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
         if (StrUtil.isBlankOrUndefined(entity.getDescribe()) || ObjectUtil.isEmpty(entity.getMetadata()))
         {
             logger.info("Failed to save operation log, operation content and operation information cannot be empty");
             return;
         }
         entity.setId(UUID.randomUUID().toString());
         entity.setUserId(entity.getMetadata().getCreatedByUserId());
         entity.setUsername(entity.getMetadata().getCreatedByUsername());
         PgUtil.postgresClient(vertxContext, okapiHeaders).save(NOTIFY_TABLE,entity,reply->{
             logger.debug("Save Party Save Operation Log Success");
        });
    }


    @Override
    public void getPartyLog(String query, int offset, int limit, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        CQLWrapper cql = null;
        try {
            cql = PartyUtil.getCQL(query, limit, offset,NOTIFY_TABLE);

        } catch (Exception e) {
            ValidationHelper.handleError(e, asyncResultHandler);
            return;
        }
        PgUtil.postgresClient(vertxContext, okapiHeaders)
                .get(NOTIFY_TABLE, org.folio.rest.jaxrs.model.PartyLogGroup.class, new String[]{"*"}, cql,
                        true , false ,
                        reply -> {
                            if (reply.succeeded()) {
                                PartyLogCollection notes = new PartyLogCollection();
                                @SuppressWarnings("unchecked")
                                List<PartyLogGroup> notifylist
                                        = reply.result().getResults();
                                notes.setPartyLogGroup(notifylist);
                                Integer totalRecords = reply.result().getResultInfo().getTotalRecords();
                                notes.setTotalRecords(totalRecords);
                                asyncResultHandler.handle(succeededFuture(
                                        GetPartyLogResponse.respond200WithApplicationJson(notes)));
                            } else {
                                ValidationHelper.handleError(reply.cause(), asyncResultHandler);
                            }
                        });
    }
}
